package com.example.thegreatwall.utils;


import com.example.thegreatwall.entity.Users;
import com.example.thegreatwall.service.UsersService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.data.redis.core.RedisTemplate;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 文晓平
 * @version 1.0
 * @Description 获取用户信息的通用类
 * @date 2025/6/2 19:24
 */
public class UserContextUtil {

    public static ResponseEntity<?> getCurrentUser(HttpServletRequest request, RedisTemplate<String, String> redisTemplate, UsersService userService) {
        String authHeader = request.getHeader("Authorization");

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Token 缺失");
        }

        String token = authHeader.substring(7);

//        String openidFromRedis = redisTemplate.opsForValue().get(ProFixRedis.TOKEN + token);
//        if (openidFromRedis == null) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("登录已失效，请重新登录");
//        }

        if (!JwtUtil.isTokenValid(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token");
        }

        String openid = JwtUtil.getOpenidFromToken(token);
        if (openid == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无法获取 openid");
        }

        Users user = userService.findOrCreateUser(openid);
        return ResponseEntity.ok(BaseResponse.success(user));
    }

    // 额外方法：直接获取 User 实体（不包装 ResponseEntity，用于业务逻辑中）
    public static Users extractUser(HttpServletRequest request, RedisTemplate<String, String> redisTemplate, UsersService userService) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return null;
        }

        token = token.substring(7);
        String openid = JwtUtil.getOpenidFromToken(token);
//        if (openid == null || redisTemplate.opsForValue().get(ProFixRedis.TOKEN + token) == null) {
//            return null;
//        }

        return userService.findOrCreateUser(openid);
    }
}